package com.hariro.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar.LayoutParams;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.hariro.activity.WebToBuyActivity;
import com.hariro.customview.CustomGridView;
import com.hariro.customview.CustomListView;
import com.hariro.customview.CustomListView_user;
import com.hariro.helper.HttpClientHelper;
import com.hariro.helper.JsonHelper;
import com.hariro.helper.MySQLiteOpenHelper;
import com.hariro.main.UILApplication;
import com.qianfeng.project.R;

public class New_Detail_Fragment extends Fragment implements OnClickListener,
		OnItemClickListener {
	private static final String urlStart = "http://mobileapi.j.cn/?method=detailv2&uid=868033010199109&imgSize=mid2&longitude=4.9E-324&latitude=4.9E-324&v=2.0&actionFrom=Stream&itemId=";
	private static final String urlEnd = "&sessionData=GqcBClQKDzg2ODAzMzAxMDE5OTEwOSI5RGFsdmlrLzEuNi4wIChMaW51eDsgVTsgQW5kcm9pZCA0LjIuMTsgTTA0MCBCdWlsZC9KT1A0MEQpKAAwwZLDuAsSMwj208afBRIkZGI3Y2VhNGUtMzEyMi00OGEzLTgwYTgtNDRiOWZmNDk0NWMyIOgHMAE4CiIaCKS1yQEQAB0AAJxCIOsBKQAAAAAAAAAAWAE&net=wifi";
	private TextView text_shopdetail_title;
	private TextView text_shopdetail_price;
	private TextView text_shopdetail_volume;
	private TextView text_shopdetail_shop;
	private TextView text_main_morepic;
	private TextView text_mastername;
	private TextView text_main_moreAssess;
	private TextView text__askfriends;
	private TextView text__sharetofriends;
	private TextView text_noContent;
	private TextView text_tab_newstyle;
	private TextView text_commitem_share;
	private TextView text_itemcomm_collection;
	private ImageView imageview_common_collection_icon_up;
	private ImageView ImageView_tobuy;
	private boolean flag;
	private List<Map<String, Object>> list_others = null;
	private List<Map<String, Object>> recommendItems = null;
	private List<Map<String, Object>> tags = null;
	private List<Map<String, Object>> thumbnails = null;
	private List<Map<String, Object>> comments = null;
	private CustomListView listView_thumb = null;
	// private ListView listView_thumb = null;
	private CustomListView_user listview_shop_userassess = null;
	private CustomGridView gridView_recommend = null;
	private ScrollView scrollView_newshop;
	private PopupWindow popupWindow = null;
	private View popup_view = null;
	private String itemId;
	private String typeId;
	private MySQLiteOpenHelper mySQLiteOpenHelper;
	private static final String DBNAME = "MyNewStyle.db";
	private static final int VERSION = 1;
	private MyDetailsAdapter myAdapterpic = null;
	private MyDetailsAdapter myAdapterassas = null;
	private int morepic;
	private int moreassas;
	private ProgressDialog pd;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				pd.show();// 显示进度对话框
				break;
			case 1:
				pd.hide();// 隐藏进度对话框，不可使用dismiss()、cancel(),否则再次调用show()时，显示的对话框小圆圈不会动。
				break;
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		list_others = new ArrayList<Map<String, Object>>();
		recommendItems = new ArrayList<Map<String, Object>>();
		tags = new ArrayList<Map<String, Object>>();
		thumbnails = new ArrayList<Map<String, Object>>();
		comments = new ArrayList<Map<String, Object>>();
		if (mySQLiteOpenHelper == null) {
			mySQLiteOpenHelper = new MySQLiteOpenHelper(getActivity(), DBNAME,
					null, VERSION);
		}
		pd = new ProgressDialog(getActivity());
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setMessage("数据载入中，请稍候！");
	}

	@SuppressWarnings("deprecation")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_shop_detail, null);
		handler.sendEmptyMessage(0);
		Bundle bundle = getArguments();
		itemId = bundle.getString("itemId");
		typeId = bundle.getString("typeId");
		text_shopdetail_title = (TextView) view
				.findViewById(R.id.text_shopdetail_title);
		text_shopdetail_price = (TextView) view
				.findViewById(R.id.text_shopdetail_price);
		text_shopdetail_volume = (TextView) view
				.findViewById(R.id.text_shopdetail_volume);
		text_shopdetail_shop = (TextView) view
				.findViewById(R.id.text_shopdetail_shop);
		text_main_morepic = (TextView) view
				.findViewById(R.id.text_main_morepic);
		text_mastername = (TextView) view.findViewById(R.id.text_mastername);
		text_main_moreAssess = (TextView) view
				.findViewById(R.id.text_main_moreAssess);
		text__askfriends = (TextView) view.findViewById(R.id.text__askfriends);
		text__sharetofriends = (TextView) view
				.findViewById(R.id.text__sharetofriends);
		text_noContent = (TextView) view.findViewById(R.id.text_noContent);
		listView_thumb = (CustomListView) view.findViewById(R.id.listView_pic);
		gridView_recommend = (CustomGridView) view
				.findViewById(R.id.gridView_shop_guess);
		listview_shop_userassess = (CustomListView_user) view
				.findViewById(R.id.listview_shop_userassess);
		scrollView_newshop = (ScrollView) view
				.findViewById(R.id.scrollView_newshop);

		// View layout = getActivity().getLayoutInflater().inflate(
		// R.layout.comm_share_collect_buy, null);
		// text_item_share = (TextView)
		// layout.findViewById(R.id.text_item_share);
		// text_item_share.setOnClickListener(this);
		// 代码里去掉listview的焦点
		listView_thumb.setFocusable(false);
		listview_shop_userassess.setFocusable(false);
		gridView_recommend.setFocusable(false);
		scrollView_newshop.smoothScrollTo(0, 20);
		// 异步加载店铺所有数据
		String urlString = urlStart + itemId + urlEnd;
		loadData(urlString);
		// text_tab_newstyle.setOnClickListener(this);
		// 找到include 的控件
		LinearLayout layout = (LinearLayout) view
				.findViewById(R.id.comm_share_coll_tobuy);
		text_commitem_share = (TextView) layout
				.findViewById(R.id.text_commitem_share);
		imageview_common_collection_icon_up = (ImageView) layout
				.findViewById(R.id.imageview_common_collection_icon_up);
		text_itemcomm_collection = (TextView) layout
				.findViewById(R.id.text_itemcomm_collection);
		ImageView_tobuy = (ImageView) layout.findViewById(R.id.ImageView_tobuy);

		text_itemcomm_collection.setTag(getId(), 3333);
		text_commitem_share.setTag(getId(), 1111);
		imageview_common_collection_icon_up.setTag(getId(), 2222);
		ImageView_tobuy.setTag(getId(), 4444);
		// ///
		text_main_morepic.setOnClickListener(this);
		text_main_moreAssess.setOnClickListener(this);

		// /////
		text_commitem_share.setOnClickListener(this);
		imageview_common_collection_icon_up.setOnClickListener(this);
		text_itemcomm_collection.setOnClickListener(this);
		ImageView_tobuy.setOnClickListener(this);
		gridView_recommend.setOnItemClickListener(this);
		popup_view = getActivity().getLayoutInflater().inflate(
				R.layout.dialog_share_menu, null);
		popupWindow = new PopupWindow(popup_view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources()));
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popup_view.setOnTouchListener(new OnTouchListener()// 需要设置，点击之后取消popupview，即使点击外面，也可以捕获事件
				{
					public boolean onTouch(View v, MotionEvent event) {
						if (popupWindow.isShowing()) {
							// Trace.Log("-------------------onTouch------------");
							popupWindow.dismiss();
						}
						return false;
					}
				});
		return view;
	}

	private void loadData(String url) {
		new MyTask(getActivity()).execute(url);
	}

	class MyTask extends AsyncTask<String, Void, String> {
		// List<List<Map<String, Object>>>
		private Context context;

		// private int key;
		public MyTask(Context context) {
			this.context = context;

		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			// List<List<Map<String, Object>>> lists = new
			// ArrayList<List<Map<String, Object>>>();
			String data = new String(
					HttpClientHelper.loadByteFromURL(params[0]));
			if (data != null) {
				return data;
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				JSONObject object = null;
				Map<String, Object> map = new HashMap<String, Object>();
				try {
					object = new JSONObject(result);
					object = new JSONObject(result);
					map.put("title", object.getString("title"));
					map.put("price", object.getString("price"));
					map.put("volume", object.getString("volume"));
					map.put("xksName", object.getString("xksName"));
					map.put("shopName", object.getString("shopName"));
					map.put("numId", object.getString("numId"));
					map.put("buyUrl", object.getString("buyUrl"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				list_others.add(map);
				recommendItems = JsonHelper.jsonStringToList(result,
						new String[] { "imgUrl", "price", "shopId", "itemId" },
						"recommendItems");
				tags = JsonHelper.jsonStringToList(result, new String[] {
						"tagName", "weight", "tagId", "topCategoryName",
						"topCategoryId" }, "tags");
				thumbnails = JsonHelper.jsonStringToList(result, new String[] {
						"imgUrl", "compressed", "height", "width" },
						"thumbnails");
				comments = JsonHelper.jsonStringToList(result, new String[] {
						"user", "content", "time", "result" }, "comments");
				// gridview 加载数据
				if (recommendItems != null) {
					gridView_recommend.setAdapter(new MyDetailsAdapter(
							getActivity(), recommendItems, 0, 0));
				} else {
					Toast.makeText(getActivity(), "recommendItems为空", 0).show();
				}
				// 设置店铺基本信息
				if (list_others != null) {
					text_shopdetail_title.setText(list_others.get(0)
							.get("title").toString());
					text_shopdetail_price.setText("￥"
							+ list_others.get(0).get("price").toString());
					text_shopdetail_volume.setText("已经有"
							+ list_others.get(0).get("volume").toString()
							+ "人购买");
					text_shopdetail_shop.setText("【"
							+ list_others.get(0).get("shopName").toString()
							+ "】");
					text_mastername.setText(list_others.get(0).get("xksName")
							.toString());
				} else {
					Toast.makeText(getActivity(), "list_others为空", 0).show();
				}
				// 加载大图片,加载前判断数据是否为空
				if (thumbnails.size() != 0) {
					List<Map<String, Object>> listPic = new ArrayList<Map<String, Object>>();
					if (thumbnails.size() > 5) {
						for (int i = 0; i < 5; i++) {
							listPic.add(thumbnails.get(i));
						}
						myAdapterpic = new MyDetailsAdapter(getActivity(),
								listPic, 1, 1);
					} else {
						myAdapterpic = new MyDetailsAdapter(getActivity(),
								thumbnails, 1, 1);
						text_main_morepic.setVisibility(View.GONE);
					}
					listView_thumb.setAdapter(myAdapterpic);

				} else {
					text_main_morepic.setVisibility(View.GONE);
					Toast.makeText(getActivity(), "展示图片为空", 0).show();
				}
				// 加载评论，判断评论是否为空
				if (comments.size() != 0) {
					if (comments.size() > 6) {
						List<Map<String, Object>> listAssas = new ArrayList<Map<String, Object>>();
						for (int i = 0; i < 6; i++) {
							listAssas.add(comments.get(i));
						}
						myAdapterassas = new MyDetailsAdapter(getActivity(),
								listAssas, 2, 2);
					} else {
						myAdapterassas = new MyDetailsAdapter(getActivity(),
								comments, 2, 2);
						text_main_moreAssess.setVisibility(View.GONE);
					}
					listview_shop_userassess.setAdapter(myAdapterassas);
				} else {
					text_main_moreAssess.setVisibility(View.GONE);
					Toast.makeText(getActivity(), "评论为空", 0).show();
					text_noContent.setVisibility(View.VISIBLE);
				}
				handler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
			} else {
				Toast.makeText(getActivity(), "网络获取数据失败！", 0).show();
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.text_commitem_share:
			if (popupWindow.isShowing()) {
				popupWindow.dismiss();
			} else {
				popupWindow.showAtLocation(popup_view, Gravity.BOTTOM, 0, 0);
			}
			break;
		case R.id.text_itemcomm_collection:
			if (!flag) {
				// 查询语句
				String select = "select itemId from tb_collect where itemId=?";
				// 插入语句
				String sql = "insert into tb_collect (itemId , typeId) values (?,?)";
				int count = mySQLiteOpenHelper.selectCount(select,
						new String[] { itemId });
				// SQL语句 插入新数据前，先 判断该数据是否存在
				if (count == 0) {
					mySQLiteOpenHelper.updateData(sql, new String[] { itemId,
							typeId });
					Toast.makeText(getActivity(), "收藏成功！", Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(getActivity(), "该文章已收藏！", Toast.LENGTH_SHORT)
							.show();
				}
				// 点击显示对应文字
				text_itemcomm_collection.setText("取消收藏");
				imageview_common_collection_icon_up
						.setImageResource(R.drawable.common_collection_icon_down);
				flag = true;
			} else {
				// 查询语句
				String select = "select itemId from tb_collect where itemId=?";
				// 删除语句 、、delete from exam_questions where id<2000;
				String sql = "delete from tb_collect where itemId=?";
				int count = mySQLiteOpenHelper.selectCount(select,
						new String[] { itemId });
				// 先 判断该数据是否存在
				if (count != 0) {
					mySQLiteOpenHelper.updateData(sql, new String[] { itemId });
					Toast.makeText(getActivity(), "取消成功！", Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(getActivity(), "该商品没有收藏！",
							Toast.LENGTH_SHORT).show();
				}
				text_itemcomm_collection.setText("收藏");
				flag = false;
				imageview_common_collection_icon_up
						.setImageResource(R.drawable.common_collection_icon_up);
			}
			break;
		case R.id.ImageView_tobuy:
			Intent intent = new Intent(getActivity(), WebToBuyActivity.class);
			String buyUrl = list_others.get(0).get("buyUrl").toString();
			intent.putExtra("buyUrl", buyUrl);
			Toast.makeText(getActivity(), buyUrl, 0).show();
			startActivity(intent);
			break;
		case R.id.text_main_morepic:
			List<Map<String, Object>> listPic = new ArrayList<Map<String, Object>>();
			if ((morepic + 4) <= thumbnails.size() - 5) {
				morepic += 3;
				for (int i = 0; i < morepic + 5; i++) {
					listPic.add(thumbnails.get(i));
				}
				myAdapterpic.setArrayList(listPic);
				myAdapterpic.notifyDataSetChanged();
				if ((morepic + 3) >= thumbnails.size()) {
					text_main_morepic.setVisibility(View.GONE);
				}
			} else {
				myAdapterpic.setArrayList(thumbnails);
				myAdapterpic.notifyDataSetChanged();
				text_main_morepic.setVisibility(View.GONE);
				Toast.makeText(getActivity(), "没有图片了！", 0).show();
			}
			Toast.makeText(getActivity(), morepic + "", 0).show();
			break;
		case R.id.text_main_moreAssess:
			List<Map<String, Object>> listAssas = new ArrayList<Map<String, Object>>();
			if ((moreassas + 6) <= comments.size() - 6) {
				moreassas += 5;
				for (int i = 0; i < moreassas + 6; i++) {
					listAssas.add(comments.get(i));
				}
				myAdapterassas.setArrayList(listAssas);
				myAdapterassas.notifyDataSetChanged();
				if ((moreassas + 5) >= comments.size()) {
					text_main_moreAssess.setVisibility(View.GONE);
				}
			} else {
				if (comments.size() == 0) {
					text_main_moreAssess.setVisibility(View.GONE);
				} else {
					myAdapterassas.setArrayList(comments);
					myAdapterassas.notifyDataSetChanged();
					text_main_moreAssess.setVisibility(View.GONE);
					// Toast.makeText(getActivity(), "没有评论了！", 0).show();
				}
			}
			Toast.makeText(getActivity(), moreassas + "", 0).show();
			break;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		// Map<String, Object> map = new HashMap<String, Object>();
		// map = (Map<String, Object>) parent.getChildAt(position);
		String itemId = recommendItems.get(position).get("itemId").toString();
		loadData(urlStart + itemId + urlEnd);
	}
}

class MyDetailsAdapter extends BaseAdapter {
	private List<Map<String, Object>> list = null;
	private Context context;
	private int key;
	private int count;

	public MyDetailsAdapter(Context context, List<Map<String, Object>> list,
			int key, int count) {
		this.context = context;
		this.list = list;
		this.key = key;
		this.count = count;
	}

	public void setArrayList(List<Map<String, Object>> list) {
		this.list = list;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder mHolder = null;
		if (convertView == null) {
			mHolder = new ViewHolder();

			if (key == 0) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_shop_recommend, parent, false);
			}
			if (key == 1) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_shop_thumbnails, parent, false);
			}
			if (key == 2) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_shop_comments, parent, false);
			}
			mHolder.imageView_item_gridview_pic = (ImageView) convertView
					.findViewById(R.id.imageView_item_gridview_pic);
			mHolder.text_item_gridview_price = (TextView) convertView
					.findViewById(R.id.text_item_gridview_price);
			mHolder.imageView_item_thumb = (ImageView) convertView
					.findViewById(R.id.imageView_item_thumb);

			mHolder.text_item_content = (TextView) convertView
					.findViewById(R.id.text_item_content);
			mHolder.text_item_user = (TextView) convertView
					.findViewById(R.id.text_item_user);
			mHolder.text_item_time = (TextView) convertView
					.findViewById(R.id.text_item_time);
			convertView.setTag(mHolder);
		} else {
			mHolder = (ViewHolder) convertView.getTag();
		}
		if (key == 0) {
			mHolder.text_item_gridview_price.setText("￥"
					+ list.get(position).get("price").toString());
			String imgUrl = list.get(position).get("imgUrl").toString();
			// 缓存后再异步加载图片
			UILApplication.imageLoader.displayImage(imgUrl,
					mHolder.imageView_item_gridview_pic,
					UILApplication.options, null);
		}
		if (key == 1) {
			int height = Integer.parseInt(list.get(position).get("height")
					.toString());
			AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT, height);
			convertView.setLayoutParams(lp);
			String imgUrl = list.get(position).get("imgUrl").toString();
			// 缓存后再异步加载图片
			mHolder.imageView_item_thumb.setScaleType(ScaleType.CENTER_CROP);
			UILApplication.imageLoader.displayImage(imgUrl,
					mHolder.imageView_item_thumb, UILApplication.options, null);
		}
		if (key == 2) {
			// "user", "content", "time",
			SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
			mHolder.text_item_content.setText(list.get(position).get("content")
					.toString());
			mHolder.text_item_user.setText("买家 "
					+ list.get(position).get("user").toString());
			long aa = Long.parseLong(list.get(position).get("time").toString()
					+ "000");
			String retStrFormatNowDate = sdFormatter.format(aa);
			mHolder.text_item_time.setText("时间 " + retStrFormatNowDate);
		}

		return convertView;
	}

	class ViewHolder {
		private TextView text_item_content;
		private TextView text_item_user;
		private TextView text_item_time;

		private TextView text_item_gridview_price;
		private ImageView imageView_item_gridview_pic;
		private ImageView imageView_item_thumb;
	}
}
